package com.yoke.service.rewrite;

import com.alibaba.fastjson.JSONObject;
import com.github.odiszapc.nginxparser.NgxBlock;
import com.github.odiszapc.nginxparser.NgxConfig;
import com.github.odiszapc.nginxparser.NgxEntry;
import com.github.odiszapc.nginxparser.NgxParam;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by jiangzeyin on 2017/5/11.
 */
@Service
public class RewriteIndexService extends RewriteBaseService {


    // public static final File FILE = new File(confPath);


    public File getConfFile() {
        return new File(getConfPath());
    }


    public String[] listNames() {
        File file = new File(getConfPath());
        if (!file.exists())
            return null;
        return file.list();
    }

    public JSONObject getConfRoot(String path) throws IOException {
        NgxConfig conf = NgxConfig.read(path);
        List<NgxEntry> locations = conf.findAll(NgxConfig.BLOCK, "server", "location");
        NgxParam server_name = conf.findParam("server", "server_name");
        JSONObject jsonObject = new JSONObject();
        if (server_name != null) {
            List<String> server_names = server_name.getValues();
            jsonObject.put("server_name", server_names);
        }
        if (locations == null)
            return jsonObject;
        for (NgxEntry ngxEntry : locations) {
            if (ngxEntry instanceof NgxBlock) {
                NgxBlock block = (NgxBlock) ngxEntry;
                String loc_url = block.getValue();
                if ("/".equals(loc_url)) {
                    NgxParam ngxParam = block.findParam("root");
                    if (ngxParam != null) {
                        String rootPath = ngxParam.getValue();
                        jsonObject.put("rootPath", rootPath);
                    }
                    //System.out.println(ngxParam.getValue());
                }
                //System.out.println();
            }
        }
        return jsonObject;
    }
}
